import { useEffect, useMemo, useRef, useState } from "react";
import { listType, delType, saveType, exportType, refreshCache } from '@/api/system/dict/type'

import SearchForm from "../../../components/searchForm";
import { Table, Space, Divider, Button, message, Modal } from "antd";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { download, parseTime } from "../../../utils";
import { ModalForm, ProForm, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import DictTypeForm from "./modules/dictTypeForm";
import DictDataIndex from "./dictDataIndex";


const queryItems = [
  {
    name: 'dictName',
    label: '字典分类名称',
    type: 'INPUT',
  },
  {
    name: 'dictType',
    label: '字典分类编码',
    type: 'INPUT',
  }
];


//i18n
const DictIndex = () => {
  const [searchParams, setSearchParams] = useState({});
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '字典分类名称',
      dataIndex: 'dictName',
      ellipsis: true,
      align: 'left'
    },
    {
      title: '字典分类编码',
      dataIndex: 'dictType',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '描述',
      dataIndex: 'remark',
      ellipsis: true,
      align: 'left'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      align: 'center',
      render: (_, { createTime }) => (
        <>
          {parseTime(createTime)}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '10%',
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改【${record.dictName}】类型`}
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <DictTypeForm />
          </ModalForm>

          {
            record.parentId != 0 && <Divider type="vertical" />
          }
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];
  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-dict-listType', page, searchParams],
    queryFn: () => {
      return listType({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...searchParams,
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })


  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }
  const onExpandCurrent = (expandedKeys, row) => {
    if (expandedKeys) {
      setExpandedRowKeys([row.id])
    } else {
      setExpandedRowKeys([])
    }
  }

  const handleRefreshCache = () => {
    refreshCache().then(() => {
      message.success('刷新成功')
    })
  }

  const handleSave = (values) => {
    return saveType({ ...values, dictCode: values.dictType }).then(() => {
      refetch()
      if (values.id) {
        message.success('修改成功')
      } else {
        message.success('新增成功')
      }
      return true
    })
  }

  const deleteConfirm = (row) => {
    const dictIds = row.id || selectedRowKeys
    const dictNames = row.dictName || selectedRows.map(d => d.dictName)
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: `当前选中字典编号为"${dictNames}"的数据`,
      autoFocusButton: null,
      onOk() {
        return delType(dictIds)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const exportConfirm = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportType({
          pageNum: page.pageNo,
          pageSize: page.pageSize,
          ...searchParams,
        })
          .then(response => {
            download(response.msg)
            message.success('导出成功')
          })
      },
      onCancel() { },
    });
  }

  return (
    <div size="small" className="searchTableWrapper">
      <div className="searchTableHeader">字典管理</div>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(searchParams)) {
            setSearchParams({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        buttons={<>
          <ModalForm
            trigger={<Button className="ml-2" icon={<PlusOutlined />} type="primary">新增</Button>}
            title="添加字典类型"
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            grid={true}
          >
            <DictTypeForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
          <Button className="ml-2" onClick={exportConfirm}>导出</Button>
          <Button onClick={handleRefreshCache}>刷新缓存</Button>
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}

        expandable={{
          expandedRowKeys: expandedRowKeys,
          expandedRowRender: (record) => (
            <DictDataIndex dictType={record.dictType} dictId={record.id} title={record.dictName}></DictDataIndex>
          ),
          onExpand: onExpandCurrent,
        }}
      />
    </div>
  );
};


export default DictIndex;
